from typing import Optional
from sqlalchemy.orm import Session
from fastapi import APIRouter, HTTPException, status, Depends, Query, Path, Body
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse

from common import deps
from schemas.request.blog_sort import BlogSortAdd, BlogSortUpd
from service.blog_sort import BolgSortService

router = APIRouter()


@router.get('/sorts', description='分页查询列表')
async def get_list(
        db: Session = Depends(deps.get_db),
        page_number: int = Query(1, description='页码'),
        page_size: int = Query(10, description='条数', gt=1, le=100),
        sort_name: Optional[str] = Query(None, description='排序名称'),
        sort_order: Optional[str] = Query(None, description='排序方式'),
        name: Optional[str] = Query(None, description='名称', max_length=20),
        state: Optional[int] = Query(None, description='状态：1、启用。0、禁用。'),
):
    data = BolgSortService.get_list(db, page_number, page_size, sort_name, sort_order, name, state)
    return data
    return JSONResponse(
        content=jsonable_encoder(data), status_code=status.HTTP_200_OK
    )


@router.post('/sorts', status_code=status.HTTP_201_CREATED, description='添加数据')
async def add(
        db: Session = Depends(deps.get_db),
        obj_in: BlogSortAdd = Body(..., description='请求数据', embed=True)
):
    try:
        res = BolgSortService.add(db, obj_in=obj_in)
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, detail="Parameter error"
        )
    return JSONResponse(content=res, status_code=status.HTTP_201_CREATED)


@router.delete('/sorts/{id}', description='根据id删除')
async def delete(
        db: Session = Depends(deps.get_db),
        id: int = Path(None, description='主键id')
):
    res = BolgSortService.delete(db, ids=id)
    return JSONResponse(content=res, status_code=status.HTTP_200_OK)


@router.put('/sorts/{id}', description='根据id更新')
async def upd(
        db: Session = Depends(deps.get_db),
        id: int = Path(None, description='主键id'),
        obj_in: BlogSortUpd = Body(..., description='请求数据', embed=True)
):
    res = BolgSortService.upd(db, id=id, obj_in=obj_in)
    return JSONResponse(content=res, status_code=status.HTTP_200_OK)


@router.get('/sorts/{id}', description='根据id查询')
async def get(
        db: Session = Depends(deps.get_db),
        id: int = Path(None, description='主键id')
):
    res = BolgSortService.get(db, id=id)
    return JSONResponse(content=res, status_code=status.HTTP_200_OK)
